<?php
// 编码声明

use LDAP\Result;

header("Content-Type:text/html;charset=utf-8");

//封装的函数库

/**
*/
function notice($msg = '', $url = '')
{
    if(empty($url)) //没有跳转地址 返回上一个界面
    {
        echo "<script>alert('$msg');history.go(-1);</script>";
    }else //有地址，就跳转到指定的地址去
    {
        echo "<script>alert('$msg');location.href='$url';</script>";
    }
}

/**
 * @param string $msg 用于对错的内容
 * @param string $input 表单中input[file]name名字
 * @param string $result 判断对错
 * @return array[result=>true|false msg=>'上传成功和失败的原因' ]数组内部存储
 */
// 首先存在默认的地址

function UploadFile($input = 'file',$path = ''){
    $success = ['result'=>false,'msg'=>'','data'=>''];
    //获取文件对象 name
    $file = $_FILES[$input];
    //上传失败会出现的情况
    // var_dump($file['error']);error属性
    // exit;
    if($file['error']>0){
        switch($file['error']){
            case 1:
                $success['msg'] = '文件上传大小超过了服务器的限制';
                break;
            case 2:
                $success['msg'] = '上传文件大小超出指定的值';
                break;
            case 3:
                $success['msg'] = '网络中断';
                break;
            case 4:
                $success['msg'] = '无文件上传';
                break;
            default:
                $success['msg'] = '未知错误';
                
        }
        return $success;
    }
    //上传成功后给文件重新命名
    //获取文件的后缀
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);

    // 获取文件名
    $name = pathinfo($file['name'],PATHINFO_FILENAME);

    //获取时间挫
    $time = time();
    //随机数
    $rand = mt_rand(1111,9999);
    //拼接
    $filename = "{$name}_{$time}_{$rand}.$ext";

    //判断如果当前目录不存在 ，就直接失败
    if(!is_dir($path)){
        $success['msg']= '当前目录不存在';
        return $success;
    }
    //拼接路径
    $filename = $path.'/'.$filename;
    // var_dump($filename);
    // exit;

    //判断文件是否能够通过post上传
    if(!is_uploaded_file($file['tmp_name'])){
        $success['msg']= '文件上传不合法';
    }
    // var_dump(move_uploaded_file($file['tmp_name'], $filename));
    // exit;
    //临时的文件移动到指定目录下
    if(move_uploaded_file($file['tmp_name'], $filename)){
        $success['result']=true;
        $success['msg']= '文件上传成功';
        $success['data'] = $filename;
        // var_dump($filename);
        // exit;
    }
    else{
        $success['msg']= '文件上传失败';
    }
    return $success;
    //文件上传前的临时文件名字
    // var_dump($file['tmp_name']);
    // exit;


    // 获取文件名加后缀
    //name相当于 file里面的key
    // var_dump($file['name']);
    // exit;

}
// 一个长度为10的随机字符串
if (!function_exists('randstr')) {
    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    function randstr($len = 10, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

/* 
*   获取当前的网址   
*/

function get_url()
{
    // 获取当前的完整地址
    $str = $_SERVER['PHP_SELF'] . '?';

    if($_GET){
        foreach($_GET as $k => $v){
            if($k != 'page'){
                $str.= $k.'='.$v.'&';
            }
        }
    }

    return $str;
}

/**
 * 输出分页函数
 * @param $current 当前页
 * @param $count   记录总数(查询数据表的总数)
 * @param $limit   每页显示多少条
 * @param $size    显示页码
 * @param $class   样式
 */
function page($current, $count, $limit, $size, $class = 'digg')
{
    $page = '';

    // 判断是否显示分页
    if ($count > $limit) {
        // 总分页
        $pages = ceil($count / $limit);

        // 获取地址
        $url = get_url();

        $page .= '<div class="' . $class . '">';

        // 首页 上一页
        if ($current == 1) {
            $page .= '<span class="disabled">首&nbsp;页</span>';
            $page .= '<span class="disabled">上一页</span>';
        } else {
            $page .= '<a href="' . $url . 'page=1">首&nbsp;页</a>';
            $page .= '<a href="' . $url . 'page=' . ($current - 1) . '">上一页</a>';
        }

        // 中间部分显示页码，  取的页码范围
        if ($current <= floor($size / 2)) {
            // 当前页在中间位置靠左,floor()向下取整
            $start  =  1;
            // 如果总页数大于中间显示多少页,结束数字就是中间显示多少页的数字,否则结束数字就是总页数
            $end = $pages < $size ? $pages : $size;
        } else if ($current >= $pages - floor($size / 2)) {
            // 当前页在中间位置靠右 避免页数出现0或者负数
            $start = $pages - $size + 1 <= 0 ? 1 : $pages - $size + 1;
            $end = $pages;
        } else {
            // 当前页刚好在中间位置
            $start = $current - floor($size / 2);
            $end = $current + floor($size / 2);
        }

        for ($i = $start; $i <= $end; $i++) {
            if ($i == $current) {
                $page .= '<span class="current">' . $i . '</span>';
            } else {
                $page .= '<a href="' . $url . 'page=' . $i . '">' . $i . '</a>';
            }
        }

        // 下一页 尾页
        if ($pages == $current) {
            $page .= '<span class="disabled">下一页</span>';
            $page .= '<span class="disabled">尾&nbsp;页</span>';
        } else {
            $page .= '<a href="' . $url . 'page=' . ($current + 1) . '">下一页</a>';
            $page .= '<a href="' . $url . 'page=' . $pages . '">尾&nbsp;页</a>';
        }

        $page .= '</div>';
    }

    return $page;
}
//获取默认地址
function GetLocation(){
    global $connect;
    global $pre_;
    $str = file_get_contents("http://ip-api.com/json/");
    if(empty($str)){
        return '';
    }
    //把json形式的文件转换 成php数组形式
    $citys = json_decode($str,true);

    $city = isset($citys['city'])?trim($citys['city']):'';
    if(empty($city)){
        return '';
    }

    $sql = "SELECT name,province FROM {$pre_}region WHERE citypinyin = '$city'";
    $region = select($sql);

    return $region;
}
//GetWeather 获取天气等数据
function GetWeather($city){
    global $connect;
    global $pre_;
 // https://query.asilu.com/weather/baidu/?city=%27%E5%B9%BF%E5%B7%9E%27 获取添加的 api接口
    $str = file_get_contents("https://query.asilu.com/weather/baidu/?city='$city'");
    if(empty($str)){
        return "";
    }

    $result = json_decode($str,true);
    //获取天气接口中的数据
    $date = isset($result["date"])?trim($result["date"]):date("m-d",time());
    $weather = isset($result["weather"][0]) ? $result["weather"][0] : [];

    // return $weather;
    if(empty($weather)){
        return "暂无天气信息！";
    }
    $wet = $weather["weather"];
    $temp = $weather["temp"];
    $wind = $weather["wind"];
    //拼接字符串
    $StrHtml = $date."气候转向:".$wet."温度:".$temp."后".$wind;

    return $StrHtml;
}


//单条件查询 全查 封装方法
function select($sql){
    global $connect;
    $result = mysqli_query($connect,$sql);

    if(!$result){
        notice('查询不到错误');
        exit;
    }
    //查询到返回值
    return mysqli_fetch_assoc($result);
}

//多条数据查询
function selectAll($sql){
    global $connect;
    $result = mysqli_query($connect,$sql);
    if(!$result){
        notice('查询不到错误');
        exit;
    }
    //查询的数据以关联数据的形式返还
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

//添加方法
function insert($table,$data = []){
    global $connect;
    global $pre_;
    $table = $pre_.$table;
   
    //将数组的所有key下标放在一个新的数组中
    $key = array_keys($data);

    // implode 是将数组转化成字符串
    $key = '`'.implode('`,`',$key).'`';
    $value = "'".implode("','",$data)."'";
    // echo $key;
    // echo $value;
    // exit;
    // $value = 
    $sql = "INSERT INTO $table ($key) VALUE ($value)";
    // echo $sql ;
    // exit;
    $result = mysqli_query($connect,$sql);

    if(!$result){
        notice('添加条件错误!');
        exit;
    }

    return mysqli_insert_id($connect);

}
//修改
function edit($table,$data,$where = 1){
    global $connect;
    global $pre_;
    $table = $pre_.$table;
    // var_dump($data);
    // exit;
    $str = '';
    // 拼接字符串
    foreach($data as $key => $value){
        $str .= "`$key` = '$value' ,";
    }
    $str = trim($str,',');
    $sql = "UPDATE $table SET $str WHERE $where";
    $res = mysqli_query($connect,$sql);
    
    if(!$res){
        notice('条件错误!');
        exit;
    }
    return mysqli_affected_rows( $connect );

}
//删除
function del($table,$where = 1){
    global $connect;
    global $pre_;
    $table = $pre_.$table;
    $sql = "DELETE FROM $table WHERE $where";
    $res = mysqli_query($connect,$sql);
    if(!$res){
        notice('条件错误!');
        exit;
    }
    return mysqli_affected_rows( $connect );
}
